package org.feng.support;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.feng.vo.SmsMessageVO;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author feng
 * @Date 2022/6/7 14:32
 * @Description TODO
 */
@Slf4j
public class AliSmsClient implements SmsClient {
    private final Client client;
    private static final ConcurrentHashMap<String, Client> MAP = new ConcurrentHashMap<>();

    public AliSmsClient(String accessKeyId, String accessKeySecret) {
        if (MAP.containsKey(accessKeyId + accessKeySecret)) {
            this.client = MAP.get(accessKeyId + accessKeySecret);
        } else {
            Config config = new Config()
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);
            config.endpoint = "dysmsapi.aliyuncs.com";
            Client client = null;
            try {
                client = new Client(config);
                MAP.put(accessKeyId + accessKeySecret, client);
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.client = client;
        }

    }

    @Override
    public Boolean sendMessage(SmsMessageVO smsMessageVO) {
        Assert.notNull(client, "未初始化阿里云短信客户端");
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(smsMessageVO.getPhoneNumbers())
                .setSignName(smsMessageVO.getSignName())
                .setTemplateCode(smsMessageVO.getTemplateCode())
                .setTemplateParam(JSON.toJSONString(smsMessageVO.getTemplateParams()));
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if ("OK".equals(sendSmsResponse.getBody().getCode())) {
                return true;
            } else {
                log.info("发送短信失败,失败代码{}，失败原因：{}", sendSmsResponse.getBody().getCode(), sendSmsResponse.getBody().getMessage());
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
